<template>
  <div class="box">
    <div class="left">
      <!-- ------------------------------------------------ -->
      <div v-for="item in testQuestionsInFo" class="bigQuestionItem">
        <div class="bigTopInFo">
          <span>{{ item.name }}</span>
          <span>(共</span>
          <span>{{ item.xiao.length }}题，</span>
          <span>)</span>
        </div>
        <div class="bigBottomInFo">
          <div v-for="xiao in item.xiao" class="bigBottomXiaoItem">
            <a
              href="#"
              @click="
                () => {
                  scrollToElement(item.sort + xiao.sort);
                  return false;
                }
              "
            >{{ xiao.sort }}</a
            >
          </div>
        </div>
        <div class="line"></div>
      </div>
      <!-- ------------------------------------------------ -->
    </div>
    <div
      id="pdfDom"
      ref="pdf"
      class="center pdf-panel"
      style="min-width: 1000px"
    >
      <div
        v-for="(item, indexBig) in testQuestionsInFo"
        ref="page-cont"
        class="topicBox"
      >


        <div class="topicBottom">
          <div class="topicBottomContent">
            <div>
              <div
                v-for="(xiao, index) in item.xiao"
                :id="item.sort + xiao.sort"
                :style="{
                  height: ((1415 )*2) + 'px'
                }"
                class="xiaoItem"
              >
                <div class="pdf-split-page pdf-group-item answerSheet"
                     style="height: 1415px;margin: 0 auto;padding: 20px 0;box-sizing: border-box">


                  <div v-if="index==0" class="topicTop">
                    <div class="bigTopInFo">
                      <span>{{ item.name }}</span>
                      <span>(共</span>
                      <span>{{ item.xiao.length }}题</span>
                      <span>)</span>
                    </div>
                  </div>
                  <div class="xiaoInFo">
                  <span>
                    {{ xiao.sort }}.{{ xiao.itemInfo.questionTypes }}
                  </span>
                    <div style="display: flex; align-items: center"></div>
                  </div>
                  <div class="xiaoContent">
                    <!-- 单选 -->
                    <template v-if="xiao.itemInfo.questionTypes == '单选题'">
                      <div
                        class="xiaoStem"
                        v-html="setContent(gogo(xiao.itemInfo.testItemContent))"
                      ></div>
                      <div class="xiaoOption">
                        <div
                          v-for="option in xiao.itemInfo.answerList"
                          class="xiaoOptionItem"
                        >
                          <el-radio
                            v-model="xiao.itemInfo.answerJ[0]"
                            :label="option.identifier"
                            disabled
                            style="display: none"
                          >{{ option.identifier }}
                          </el-radio
                          >
                          <span style="padding-left: 20px">{{
                              option.identifier
                            }}</span>
                          <div class="optionInput">
                            <div v-html="option.answerContent"></div>
                          </div>
                        </div>
                      </div>
                      <div class="analysisBox">
                        <div class="analyTitle">解析详情</div>
                        <div
                          class="anlysisHtml"
                          v-html="setContent(gogo(xiao.itemInfo.analysis))"
                        ></div>
                      </div>
                    </template>
                    <!-- 单选 -->
                    <!-- 多选 -->
                    <template v-if="xiao.itemInfo.questionTypes == '多选题'">
                      <div
                        class="xiaoStem"
                        v-html="setContent(gogo(xiao.itemInfo.testItemContent))"
                      ></div>
                      <div class="xiaoOption">
                        <div
                          v-for="option in xiao.itemInfo.answerList"
                          class="xiaoOptionItem"
                        >
                          <el-checkbox
                            :checked="
                            xiao.itemInfo.answerJ.includes(option.identifier)
                          "
                            :label="option.identifier"
                            disabled
                            style="display: none"
                          >{{ option.identifier }}
                          </el-checkbox
                          >
                          <span style="padding-left: 20px">{{
                              option.identifier
                            }}</span>
                          <div class="optionInput">
                            <div v-html="option.answerContent"></div>
                          </div>
                        </div>
                      </div>
                      <div class="analysisBox" style="display: none">
                        <div class="analyTitle">解析详情</div>
                        <div
                          class="anlysisHtml"
                          v-html="setContent(gogo(xiao.itemInfo.analysis))"
                        ></div>
                      </div>
                    </template>
                    <!-- 多选 -->
                    <!-- 判断 -->
                    <template v-if="xiao.itemInfo.questionTypes == '判断题'">
                      <div
                        class="xiaoStem"
                        v-html="setContent(gogo(xiao.itemInfo.testItemContent))"
                      ></div>
                      <div class="xiaoOption" style="margin: 15px 0">
                        <el-radio label="1">正确</el-radio>
                        <el-radio label="2">错误</el-radio>
                      </div>
                      <div class="analysisBox" style="display: none">
                        <div class="analyTitle">解析详情</div>
                        <div
                          class="anlysisHtml"
                          v-html="setContent(gogo(xiao.itemInfo.analysis))"
                        ></div>
                      </div>
                    </template>
                    <!-- 判断 -->
                    <!-- 应用 -->
                    <template v-if="xiao.itemInfo.questionTypes == '应用题'">
                      <div
                        class="xiaoStem"
                        v-html="setContent(gogo(xiao.itemInfo.testItemContent))"
                      ></div>
                      <div class="analysisBox" style="display: none">
                        <div class="analyTitle">解析详情</div>
                        <div
                          class="anlysisHtml"
                          v-html="setContent(gogo(xiao.itemInfo.analysis))"
                        ></div>
                      </div>
                    </template>
                    <!-- 应用 -->
                    <!-- 填空 -->
                    <template v-if="xiao.itemInfo.questionTypes == '填空题'">
                      <div
                        class="xiaoStem"
                        v-html="setContent(gogo(xiao.itemInfo.testItemContent))"
                      ></div>
                      <div class="xiaoOption">
                        <div
                          v-for="option in xiao.itemInfo.answerList"
                          class="xiaoOptionItem"
                        >
                          <div class="optionInput">
                            <div v-html="option.answerContent"></div>
                          </div>
                        </div>
                      </div>
                      <div class="analysisBox" style="display: none">
                        <div class="analyTitle">解析详情</div>
                        <div
                          class="anlysisHtml"
                          v-html="setContent(gogo(xiao.itemInfo.analysis))"
                        ></div>
                      </div>
                    </template>
                    <!-- 填空 -->

                    <div v-if="isPrinting" class="labelBox">


                      <div class="labelItem">
                        <span>题型辨识</span>
                        <div class="right"></div>
                      </div>
                      <div class="labelItem">
                        <span>条件翻译</span>
                        <div class="right"></div>
                      </div>
                      <div class="labelItem">
                        <span>计算</span>
                        <div class="right"></div>
                      </div>

                    </div>
                  </div>


                </div>

                <div v-if="isPrinting"
                     class="answerSheet pdf-group-item pdf-split-page"
                     style="height: 1415px;width: 666px;margin: 0 auto;box-sizing: border-box;padding: 25px 0"
                >
                  <div class="pdf-group-item"
                       style="height: calc(100% - 10px); border: 1px red solid;border-radius: 15px">
                    <div style="height: 50px;line-height: 50px;color: red;font-size: 15px;text-align: center">
                      请在各题目的答题区域内作答，超出黑色边框限定区域的答案无效！
                    </div>
                    <div style="border: 1px black solid;height: calc(100% - 100px);margin:0 10px;"></div>
                    <div style="height: 50px;line-height: 50px;color: red;font-size: 15px;text-align: center">
                      请在各题目的答题区域内作答，超出黑色边框限定区域的答案无效！
                    </div>

                  </div>


                </div>

              </div>

            </div>
          </div>
        </div>
      </div>
    </div>
    <div :style="{ display: id != '' ? 'none' : 'block' }" class="right">
      <div>
        <div class="countdown">
          <div>剩余时间</div>
          <span>{{ hours }}</span
          ><span>:</span><span>{{ minutes }}</span
        ><span>:</span><span>{{ remainingSeconds }}</span>
          <div>
            <el-button @click="handleOutput">PDF导出</el-button>
            <el-button @click="handleOutputPrintAnswers">答案导出</el-button>
          </div>
        </div>
      </div>
    </div>
    <el-dialog :visible.sync="pdfDy" title="提示" width="70%">
      <div id="messageBox">这是一段信息</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AnswersDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="AnswersDialogVisible = false"
        >确 定</el-button
        >
      </span>
    </el-dialog>


    <!-- 页头页尾 -->
    <div
      class="pdf-header"
      style="
          font-weight: bold;
          width: 1200px;
          color: rgba(0, 0, 0, 0.85);
          position: fixed;
          top: -100vh;
          height: 1px;
        "
    >
      <!--      padding: 30px 8px;-->
    </div>
    <div
      class="pdf-footer"
      style="
          font-weight: bold;
          width: 100%;
          position: fixed;
          top: -100vh;
          height: 1px;
        "
    >
      <!--      padding: 30px 8px;-->

      <div style="display: flex; justify-content: center; align-items: center; margin-top: 10px">
        第
        <div class="pdf-footer-page"></div>
        页 / 共
        <div class="pdf-footer-page-count"></div>
        页
      </div>
    </div>

    <el-dialog
      :visible.sync="AnswersDialogVisible"
      title="提示"
      custom-class="pdf-answers"
      width="100%">
      <printAnswers></printAnswers>
      <span slot="footer" class="dialog-footer">
<!--    <el-button @click="dialogVisible = false">取 消</el-button>-->
<!--    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>-->
  </span>
    </el-dialog>


  </div>
</template>
<script>
import {getSummary} from "../../../api/examPaperLibrary";
import {exportPDF} from "@/utils/htmlToPdf.js";
import docx from "html-docx-js/dist/html-docx";
import a4SizeInPixels from "@/utils/a4ToPX.js";
import {PdfLoader} from '@/utils/pdfPro/pdfLoader'
import {customPdfLoader} from '@/utils/customPdfLoad/customPdfLoad'

import printAnswers from "@/views/examPaperLibrary/management/printAnswers.vue";

export default {
  props: {
    id: {
      require: false,
      default: "",
    },
  },
  components: {
    printAnswers
  }

  ,

  data() {
    return {
      testPaperData: {},
      form: {
        bigProblem: 0, //大题数量
        questions: 0, //小题数量
        totalPoints: 0, //总分
        testPaperClassificationId: null, //试卷分类id
        examinationPaperSummaryName: "",
        examinationPaperDetailsList: [],
      },
      testQuestionsInFo: [],
      hours: "00", //时
      minutes: "00", //分
      remainingSeconds: "00", //秒
      intervalId: null, //定时器
      boxHeight: null,
      pdfDy: false,
      a4_size: a4SizeInPixels(),
      isPrinting: true,
      AnswersDialogVisible: false
    };
  },
  mounted() {
    if (this.id != "") {
      this.getTestPaperDetail(this.id);
    } else {
      this.getTestPaperDetail(this.$route.query.examinationPaperSummaryId);
    }
    this.startCountdown(3599);
  },
  updated() {
    //判断是否初始配置，若无则配置。
    if (!this.mathJax.isMathjaxConfig.bool) {
      this.mathJax.initMathjaxConfig();
    }
    this.$nextTick((_) => {
      //传入组件id，让组件被MathJax渲染
      this.mathJax.MathQueue("questionList-page");
    });
  },
  methods: {

    //获取试卷详情(回显)
    getTestPaperDetail(val) {
      getSummary(val).then((res) => {
        if (res.code == 200) {
          let obj = JSON.parse(JSON.stringify(res.data));
          delete obj.examinationPaperDetailsList;
          console.log(obj);
          this.form = obj;

          const transformedData = res.data.examinationPaperDetailsList.reduce(
            (accumulator, currentValue) => {
              // 查找是否已有相应的题号（name1）在累积器中
              const existingItem = accumulator.find(
                (item) => item.name === currentValue.bigProblem
              );
              if (existingItem) {
                // 如果找到，则向xiao数组中添加当前小题对象
                let xiaoObj = {
                  xName: currentValue.questions,
                  itemBankId: currentValue.itemBankId,
                  itemInfo: currentValue.itemBank,
                  fenzhi: currentValue.score,
                  fenzhiIsNull: false,
                  sort: currentValue.questions.split(".")[0],
                };
                existingItem.xiao.push(xiaoObj);
              } else {
                // 如果没有找到，则创建一个新对象，并初始化xiao数组

                let digQu = {
                  name: currentValue.bigProblem,
                  sort: currentValue.reserve1,
                  fenzhi: 0,
                  xiao: [
                    {
                      xName: currentValue.questions,
                      itemBankId: currentValue.itemBankId,
                      itemInfo: currentValue.itemBank,
                      fenzhi: currentValue.score,
                      fenzhiIsNull: false,
                      sort: currentValue.questions.split(".")[0],
                    },
                  ],
                };

                accumulator.push(digQu);
              }

              // 返回累积器以便进行下一次迭代
              return accumulator;
            },
            []
          ); // 初始值为空数组
          console.log(transformedData);
          // this.testQuestionsInFo = transformedData;
          this.$set(this, "testQuestionsInFo", transformedData);
        }
      });
    },

    //倒计时
    startCountdown(seconds) {
      function bu(val) {
        if (val < 10) {
          return `0${val}`;
        } else {
          return val;
        }
      }

      this.intervalId = setInterval(() => {
        this.hours = bu(Math.floor(seconds / 3600));
        this.minutes = bu(Math.floor((seconds % 3600) / 60));
        this.remainingSeconds = bu(seconds % 60);

        if (seconds <= 0) {
          clearInterval(this.intervalId);
          countdownElement.textContent = "倒计时结束!";
        } else {
          seconds--;
        }
      }, 1000);
    },
    //每个大题的总分
    setFenzhi(n) {
      // console.log(n,this);
      let amount = 0;
      n.xiao.forEach((ele) => {
        amount += Number(ele.fenzhi);
      });
      return amount;
    },
    scrollToElement(elementId) {
      var element = document.getElementById(elementId);
      if (element) {
        element.scrollIntoView({behavior: "smooth"}); // 平滑滚动
      }
    },
    //导出pdf------ 数据统计汇总为导出文件名称；my_table_1为要导出的dom元素id
    exportData() {
      console.log(this.form.examinationPaperSummaryName);
      this.pdfDy = true;
      exportPDF(this.form.examinationPaperSummaryName, "pdfDom");
    },

    exportToWord(elementId) {
      const content = this.$refs[elementId]; // 获取div元素，或者通过Vue的ref来获取
      console.log(content);
      const converted = docx.asBlob(content.outerHTML, {
        orientation: "portrait",
        margins: {top: 720},
      });

      // 创建下载链接
      const downloadLink = document.createElement("a");
      downloadLink.href = URL.createObjectURL(converted);
      downloadLink.download = "document.docx";

      // 触发下载
      downloadLink.click();
    },

    //img去除\\
    setContent(val) {
      if (!val) return;

      if (val.includes('\\\\"')) {
        let abc = val.replaceAll('\\\\"', "");
        return abc;
      } else {
        let abc = val.replaceAll('\\"', "");
        return abc;
      }
    },

    gogo(val) {
      // console.log(val);
      if (val == "" || val == null) return;
      let item = JSON.parse(JSON.stringify(val));
      let ord = /begin{array}([\s\S]*?)\\end{array}/g; // 定义正则表达式，用于匹配以 [\begin{array} 开头的字符串

      let arr = item.match(ord); // 使用 match 方法获取所有匹配项
      // console.log(arr, "arr");
      if (arr == null || arr.length == 0) return val;

      let deleP = (P) => {
        let newP = P.split("<p>");
        let a = newP.join(" ");
        let b = a.split("</p>");
        let c = b.join(" ");
        // console.log(c, "newp");
        return c;
      };

      let abc = null;
      arr.forEach((ele) => {
        abc = val.split(ele);
        abc = abc.join(deleP(ele));
      });
      return abc;
      console.log(abc, "拼接完成");
    },


    //新pdf导出测试
    handleOutput2() {
      let el = document.querySelector(`.pdf-panel`);
      var clientH = el.clientHeight;
      var clientW = el.clientWidth;
      el.style.height = el.scrollHeight + "px"; //把要导出的元素高度设置为滚动高度
      el.style.width = 1000 + "px"; //把要导出的元素
      this.isPrinting = true


      const loading = this.$loading({
        lock: true,
        text: "导出中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
        baseY: 30
      });


      const element = document.querySelector(".pdf-panel");
      const header = document.querySelector(".pdf-header");
      const footer = document.querySelector(".pdf-footer");


      console.log(element)
      const pdfLoader = new PdfLoader(element, {
        // footer: footer,
        // header: header,
        // outputType:'dataurlnewwindow',
        fileName: this.form.examinationPaperSummaryName,
        direction: "p",
        isPageMessage: true,
        baseY: 10,
        itemName: 'answerSheet',

      });

      pdfLoader.getPdf().then((res) => {
        console.log("[ 导出成功] >", res);
        loading.close();
        this.$message.success("导出成功");
        el.style.height = clientH + 'px'
        el.style.width = clientW + 'px'
        // this.isPrinting=false
      });
    },

    //自定义pdf导出
    handleOutput() {

      const loading = this.$loading({
        lock: true,
        text: "导出中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
        baseY: 30
      });


      let el = document.querySelector(`.pdf-panel`);
      var clientH = el.clientHeight;
      var clientW = el.clientWidth;
      el.style.height = el.scrollHeight + "px"; //把要导出的元素高度设置为滚动高度
      el.style.width = 1000 + "px"; //把要导出的元素

      const pdfConent = document.querySelector('.pdf-panel')
      let pdf = new customPdfLoader(pdfConent, {sliceHeight: 1415})

      pdf.getPdf().then((res) => {
        console.log(res, '456789')
        loading.close()
        el.style.height = clientH + 'px'
        el.style.width = clientW + 'px'
      });

    },

    handleOutputPrintAnswers() {
      this.AnswersDialogVisible = true
    }
  },
};
</script>

<style>

</style>

<style lang="scss" scoped>
::v-deep .pdf-answers{
  margin-top: 0px !important;
}
.box {
  display: flex;
  padding: 0 80px;
  height: 100%;
  background-color: #f1f3f8;
  position: relative;

  > .left {
    width: 300px;
    background-color: white;
    height: calc(100% - 30px);
    position: absolute;
    top: 15px;
  }

  > .center {
    //flex: 1;
    background-color: white;
    margin: 0 0 0 315px;
    //margin: 15px 15px 15px 315px;
    overflow: auto;
    min-width: 210mm;
  }

  > .right {
    width: 200px;
    margin-top: 15px;

    > div:nth-of-type(1) {
      height: 200px;
      background-color: white;
      display: flex;
      flex-direction: column;
      align-items: center;

      .countdown {
        text-align: center;

        > div {
          margin: 10px 0;
          font-size: 12px;
        }

        > span {
          color: red;
          font-size: 16px;
          font-weight: bold;
        }
      }
    }
  }
}

.bigQuestionItem {
  width: 100%;
  min-height: 50px;
  padding: 10px 15px;

  .bigTopInFo {
    display: flex;
    align-items: center;
    font-size: 14px;
  }

  .bigBottomInFo {
    padding: 15px 0;
    display: flex;
    flex-wrap: wrap;

    .bigBottomXiaoItem {
      height: 25px;
      width: 25px;
      line-height: 25px;
      text-align: center;
      border: 1px #eee solid;
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }
}

.line {
  height: 1px;
  background-color: #eee;
}

/**
题干
*/

.topicBox {
  //margin-bottom: 15px;
  /* border: 1px solid #ebeef6; */
  .topicTop {
    height: 60px;
    background-color: #f7f8fa;
    padding: 16px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;

    .el-input {
      width: 40%;
    }

    > div:nth-of-type(2) {
      display: flex;
      align-items: center;
      color: #656577;

      i {
        margin-left: 15px;
        color: #656577;
      }

      > span {
        margin-left: 15px;
      }
    }
  }

  .topicBottom {
    .topicBottomContent {
      .errBottom {
        text-align: center;
        color: #656577;
        line-height: 150px;
        font-size: 12px;
      }
    }

    .topicBottomFooter {
      height: 70px;
      display: flex;
      align-items: center;
      margin: 0 15px;
      /* border-top: 1px solid #ebeef6; */
    }
  }
}

.xiaoItem {
  padding: 0 15px;
  /* margin-bottom: 10px; */
  .xiaoInFo {
    display: flex;
    align-items: center;
    justify-content: space-between;
    /* padding: 10px 0; */
    > div {
      display: flex;
      align-items: center;

      i {
        margin-left: 5px;
        color: #656577;
      }

      > .el-form {
        .el-form-item {
          margin-bottom: 0;
        }
      }
    }
  }

  .xiaoContent {
    min-height: 400px;
    /* height: 100vh; */
    //height: 277mm;

    .xiaoStem {
      /*border: 1px solid #ebeef6;*/
      padding: 10px;
    }

    .xiaoOption {
      .el-radio-group {
        width: 100%;
      }

      .xiaoOptionItem {
        display: flex;
        align-items: center;

        .optionInput {
          width: 100%;
          flex: 1;
          /*border: 1px solid #ebeef6;*/
          margin: 5px;

          > div {
            padding: 0 10px;
          }
        }

        .optionInputBtn {
          opacity: 0;
          height: 100%;

          i {
            color: #656577;
          }
        }
      }

      .xiaoOptionItem:hover {
        /* .optionInput {
          border: 1px solid #3a63f3;
        }*/
        .optionInputBtn {
          height: 100%;
          opacity: 1;

          i {
            color: #656577;
          }
        }
      }
    }

    .analysisBox {
      display: none;

      .analyTitle {
        font-size: 14px;
        margin: 10px 0;
      }

      .anlysisHtml {
        /* border: 1px solid #ebeef6; */
        padding: 10px;
      }
    }
  }
}

#messageBox {
  max-height: 70vh;
  overflow: auto;
}

//答题卡
.answerSheet {
  box-sizing: border-box;
}


.labelBox {
  padding: 0 10px;

  .labelItem {
    height: 40px;
    //border: 1px solid red;
    margin-bottom: 10px;
    line-height: 40px;
    display: flex;

    > span {
      min-width: 80px;
    }

    .right {
      flex: 1;
      border: 1px solid red;
    }
  }
}
</style>
